//
//  ShareViewController.m
//  SportRing
//
//  Created by 微我网络 on 15/1/27.
//  Copyright (c) 2015年 HotOne. All rights reserved.
//

#import "ShareViewController.h"
#import "SRMe+Cate.h"
#import "SRSystem.h"
#import "NSDate+Ex.h"
#import "SRSystem+Cate.h"
#import "SRSystemNetService.h"
#import <UIImageView+AFNetworking.h>
#import "UIView+Screenshot.h"

@interface ShareViewController ()
{
    UIImageView *_nav;
}
@property (nonatomic,strong) UIImageView *avatar;
@property (nonatomic,strong) UILabel *name;
@property (nonatomic,strong) NSMutableArray *labels;
@property (nonatomic,strong) UIImageView *blackView;
@property (nonatomic) BOOL isSharing;

@property (nonatomic,strong) UILabel *startDate;
@property (nonatomic,copy) NSString *date;
@property (nonatomic,copy) NSString *fat;

@property (nonatomic,copy) UIImage *shareImage;

@property (nonatomic,strong) NSMutableArray *shareButtons;

@end

@implementation ShareViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _shareButtons = [NSMutableArray array];
    
    UIImageView *backGround = [[UIImageView alloc] initWithFrame:self.view.frame];
    backGround.image = [UIImage imageNamed:@"侧边栏"];
    [self.view addSubview:backGround];
    
    [self loadFakeNavigation];
    [self initDataSource];
    [self initializeUserInterface];
    [self initBlackView];
}

- (void)initBlackView {
    
    _blackView = [[UIImageView alloc] initWithFrame:self.view.frame];
    _blackView.image = [UIImage imageNamed:@"blackCover"];
    _blackView.alpha = 0;
    _blackView.userInteractionEnabled = YES;
    [self.view addSubview:_blackView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(share)];
    [_blackView addGestureRecognizer:tap];
    
    NSArray *buttonImage = @[@"qZone",@"weChat",@"webo"];
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(CGRectGetMidX(self.view.frame)-25, CGRectGetHeight(self.view.frame), 50, 50);
        button.tag = 300+i;
        button.layer.cornerRadius = 25;
        button.layer.masksToBounds = YES;
        [button setImage:[UIImage imageNamed:buttonImage[i]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(shareWithButton:) forControlEvents:UIControlEventTouchUpInside];
        [_blackView addSubview:button];
        [_shareButtons addObject:button];
    }
}

- (void)initDataSource {
    
    [SRSystemNetService getUserMilepostWithSuccess:^(NSDictionary *dict) {
        
        NSDictionary *data = dict[@"data"];
        
        SRMe *me = [SRMe currentUser];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
        NSDate *thatDay = [formatter dateFromString:me.createDate];
        double lasting = [[NSDate date] timeIntervalSinceDate:thatDay];
        int days = lasting/60.f/60.f/24.f;
        
        for (int i = 0; i < 6; i++) {
            UILabel *label = _labels[i];
            if (days == 0) {
                [self setLabel:label value:@"0"];
                continue;
            }
            switch (i) {
                case 0:
                    [self setLabel:label value:[NSString stringWithFormat:@"%@",data[@"calorie"]]];
                    break;
                case 1:
                    [self setLabel:label value:[NSString stringWithFormat:@"%.1f",[data[@"mileage"] floatValue]/5000000.f]];
                    break;
                case 2:
                    [self setLabel:label value:[NSString stringWithFormat:@"%.1f",[data[@"counter"] floatValue]/1000]];
                    break;
                case 3:
                    [self setLabel:label value:[NSString stringWithFormat:@"%.1f",[data[@"calorie"] floatValue]/days]];
                    break;
                case 4:
                    [self setLabel:label value:[NSString stringWithFormat:@"%.1f",[data[@"mileage"] floatValue]/5000000.f/days]];
                    break;
                case 5:
                    [self setLabel:label value:[NSString stringWithFormat:@"%.0f",[data[@"counter"] floatValue]/days]];
                    break;
                    
                default:
                    break;
            }
        }
        [self setDate:[thatDay formattedBy_yyyyMMdd]];
        [self setFat:[NSString stringWithFormat:@"%ld",[data[@"calorie"] integerValue]/9]];
        
    } fail:^(NSError *error) {
        
    }];
    
}

- (void)loadFakeNavigation {
    
    _nav = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
//    _nav.image = [UIImage imageNamed:@"nav_amount"];
    _nav.userInteractionEnabled = YES;
    [self.view addSubview:_nav];
    
    UILabel *fakeTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    fakeTitle.text = @"分享";
    fakeTitle.textAlignment = NSTextAlignmentCenter;
    fakeTitle.font = [UIFont boldSystemFontOfSize:20];
    fakeTitle.textColor = [UIColor whiteColor];
    fakeTitle.center = CGPointMake(_nav.center.x, CGRectGetMaxY(_nav.frame)-20);
    [_nav addSubview:fakeTitle];
    
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    back.frame = CGRectMake(0, 24, 60, 40);
    back.imageEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 34);
    [back addTarget:self action:@selector(popPrevious) forControlEvents:UIControlEventTouchUpInside];
    [_nav addSubview:back];
    
    UIButton *share = [UIButton buttonWithType:UIButtonTypeCustom];
    [share setImage:[UIImage imageNamed:@"shareButton"] forState:UIControlStateNormal];
    share.frame = CGRectMake(CGRectGetMaxX(_nav.frame)-60, 24, 60, 40);
    [share addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    share.imageEdgeInsets = UIEdgeInsetsMake(8, 22, 10, 21);
    [_nav addSubview:share];
}

- (void)popPrevious {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)share {
    
    if (!_isSharing) {
        _nav.hidden = YES;
        _shareImage = [self.view screenshot:NO];
        _nav.hidden = NO;
        [UIView animateWithDuration:0.5 delay:0.0 usingSpringWithDamping:0.8 initialSpringVelocity:24 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            _blackView.alpha = 1;
            for (int i = 0;i < _shareButtons.count;i++) {
                UIButton *button = _shareButtons[i];
                button.center = CGPointMake(80+80*i, CGRectGetHeight(self.view.frame)-90);
            }
        } completion:^(BOOL finished) {
            _isSharing = !_isSharing;
        }];
    }
    else {
        [UIView animateWithDuration:0.2 animations:^{
            
            _blackView.alpha = 0;
            for (int i = 0;i < _shareButtons.count;i++) {
                UIButton *button = _shareButtons[i];
                button.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetHeight(self.view.frame)+30);
            }
        } completion:^(BOOL finished) {
            _isSharing = !_isSharing;
        }];
    }
}

- (void)initializeUserInterface {
    
    _date = @"0";
    _fat = @"0";
    self.title = @"分享";
    _avatar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    _avatar.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetHeight(self.view.frame)/4);
    _avatar.layer.borderWidth = 3;
    _avatar.layer.cornerRadius = 40;
    _avatar.layer.masksToBounds = YES;
    _avatar.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.view addSubview:_avatar];
    
    SRMe *me = [SRMe currentUser];
    [_avatar setImageWithURL:[NSURL URLWithString:me.headPhoto]
            placeholderImage:[UIImage imageNamed:@"头像"]];
    
    _name = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    _name.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetHeight(self.view.frame)/4+65);
    _name.textColor = [UIColor whiteColor];
    _name.font = [UIFont boldSystemFontOfSize:16];
    _name.textAlignment = NSTextAlignmentCenter;
    _name.text = me.nickName;
    [self.view addSubview:_name];
    
    UIImageView *line = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shareStar"]];
    line.frame = CGRectMake(15, CGRectGetMidY(self.view.frame)-30, self.view.frame.size.width-30, 13);
    line.contentMode = UIViewContentModeScaleAspectFill;
    line.clipsToBounds = YES;
    [self.view addSubview:line];
    
    _labels = [NSMutableArray array];
//    NSArray *labelName = @[@"总消耗",@"总里程",@"总步数",@"日均消耗",@"日均里程",@"日均步数"];
    CGFloat labelWidth = CGRectGetWidth(self.view.frame)/3;
    for (int i = 0; i < 6; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(labelWidth*(i%3), CGRectGetMidY(self.view.frame)+20/568.f*self.view.frame.size.height+75*(i/3), labelWidth, 50)];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:12];
        label.tag = 200 +i;
        [self setLabel:label value:@"100"];
        [self.view addSubview:label];
        [_labels addObject:label];
    }
    
    _startDate = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame)-95, CGRectGetWidth(self.view.frame), 80)];
    _startDate.font = [UIFont systemFontOfSize:13];
    _startDate.textAlignment = NSTextAlignmentCenter;
    _startDate.textColor = [UIColor whiteColor];
    _startDate.numberOfLines = 0;
    [self.view addSubview:_startDate];
    
//    [self setDate:@"2014.12.25"];
//    [self setFat:@"3999"];
}

- (void)shareWithButton:(UIButton *)sender {
    
    switch (sender.tag-300) {
            //qZone
        case 0:
            [self shareWithContenttype:0];
            break;
            //weChat
        case 1:
            [self shareWithContenttype:1];
            break;
            //weBlog
        case 2:
            [self shareWithContenttype:2];
            break;
            
        default:
            break;
    }
}


- (void)setLabel:(UILabel *)label value:(NSString *)value{
    
    NSString *title = @"";
    NSString *unit  = @"";
    switch (label.tag-200) {
        case 0:
            title = @"总计消耗";
            unit = @"千卡";
            break;
        case 1:
            title = @"总计里程";
            unit = @"千米";
            break;
        case 2:
            title = @"总计步数";
            unit = @"千步";
            break;
        case 3:
            title = @"日均消耗";
            unit = @"千卡";
            break;
        case 4:
            title = @"日均里程";
            unit = @"千米";
            break;
        case 5:
            title = @"日均步数";
            unit = @"步";
            break;
            
        default:
            break;
    }
    if (!value) {
        value = @"0";
    }
    NSString *full = [NSString stringWithFormat:@"%@\n\n%@%@",title,value,unit];
    label.text = full;
}

- (void)setDate:(NSString *)date {
    
    _date = date;
    NSString *full = [NSString stringWithFormat:@"%@开始使用手环\n\n累计消耗%@克肥肉",_date,_fat];
    _startDate.text = full;
}

- (void)setFat:(NSString *)fat {
    
    _fat = fat;
    NSString *full = [NSString stringWithFormat:@"%@开始使用手环\n\n累计消耗%@克肥肉",_date,_fat];
    _startDate.text = full;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)shareWithContenttype:(NSInteger)type
{
    [SRShare setup];//shareSDK初始化
    NSString *titleString   = @"爱魔客";
    NSString *urlString     = @"http://www.ShareSDK.cn";
    NSString *description   = @"欢迎使用 IMOC.";
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:titleString
                                       defaultContent:@""
                                                image:[ShareSDK pngImageWithImage:_shareImage]
                                                title:titleString
                                                  url:urlString
                                          description:description
                                            mediaType:SSPublishContentMediaTypeImage];
    
    
    __block ShareType sharetype;
    switch (type) {
        case 0:
            sharetype = ShareTypeQQSpace;
            break;
        case 1:
            sharetype = ShareTypeWeixiTimeline;
            break;
        case 2:
            sharetype = ShareTypeSinaWeibo;
            break;
    };
    
    [ShareSDK shareContent:publishContent type:sharetype authOptions:nil statusBarTips:NO result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSPublishContentStateSuccess)
        {
            if(sharetype == ShareTypeSinaWeibo)
            {
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"" message:@"新浪分享成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alter show];
            }
            NSLog(NSLocalizedString(@"TEXT_SHARE_SUC", @"发表成功"));
        }
        else if (state == SSPublishContentStateFail)
        {
            if(sharetype == ShareTypeSinaWeibo)
            {
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"" message:@"新浪分享失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alter show];
            }
            NSLog(NSLocalizedString(@"TEXT_SHARE_FAI", @"发布失败!error code == %d, error code == %@"), [error errorCode], [error errorDescription]);
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
